package socdev.mobile;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONObject;

import socdev.data.Commit;
import socdev.data.JSonDownloader;
import socdev.data.Project;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ListView;
import android.widget.TextView;

public class RepositoryActivity extends Activity {
	private static RepositoryActivity singleton;
    private static ListView commitsList;
    private static Commit [] commits;
    private static Handler handler;
	private static Project project;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.repository);
        
        singleton = this;
        commitsList = (ListView) findViewById(R.id.commits);
        handler = new Handler();
        project = (Project) getIntent().getExtras().get("project");
        Timer timer = new Timer();
        timer.schedule(new UpdateTimeTask(), 0, 10000);
    }
	
	
	class UpdateTimeTask extends TimerTask {
		   public void run() {
			   String data = JSonDownloader.getString(project.github);
 		   try {
 				JSONObject jsonObj = new JSONObject(data);
 				System.out.println(jsonObj);
 				JSONArray jsonArray = jsonObj.getJSONArray("commits");
 				System.out.println(jsonArray);
 				
 				commits = new Commit[jsonArray.length()];
 				System.out.println("blbost");
 				
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					JSONObject author = jsonObject.getJSONObject("author");
					
					System.out.println(jsonObject.getString("message"));
					
					commits[i] = new Commit(author.getString("name"), jsonObject.getString("committed_date"), jsonObject.getString("message"));

				}
				handler.post(new MyRunnable());
 				
 				
 				//handler.post(new MyRunnable());
 			} catch (Exception e) {
 				e.printStackTrace();
 			}
		   }
		}
	
	
	static public class MyRunnable implements Runnable {
		public void run() {
				commitsList.setAdapter(new CommitsAdapter(singleton, R.layout.commit_item, commits));
		}
	}
}

